# app.py
import logging
from flask import Flask, render_template, send_from_directory
from flask_socketio import SocketIO
import time
from FuncDefine import FUNC_MAP, BOT_SYSTEM_PROMPT, generate_image
# from MinimaxAPI import MINIMAX_API
from ERNIE_BOT_API import ERNIE_API
from config import *

app = Flask(__name__)
# app.debug = True
socketio = SocketIO(app, cors_allowed_origins="*")


ernie_api = ERNIE_API(aistudio_APIKEY, BOT_SYSTEM_PROMPT, FUNC_MAP)


# patch goto_location function
def funcimp_goto_location(**args):
    location = args.get("location") or args.get("data") or str(args)
    print(f"切换到了地点{location}")
    url = generate_image(location)
    socketio.emit("changeBackground", url)
    return "成功到达"
for func in FUNC_MAP:
    if func["func_desc"]['name'] == "goto_location":
        func["func_pointer"] = funcimp_goto_location
        break



# @app.route('/')
# def index():
#     return render_template('index.html')

# 主页路由
@app.route('/')
def index():
    return send_from_directory('static', 'index.html')

# 其他资源路由
@app.route('/<path:path>')
def send_static(path):
    # 获取文件的扩展名
    ext = path.split('.')[-1].lower()
    
    # 根据扩展名设置对应的 MIME 类型
    if ext in {'js', 'mjs'}:
        mimetype = 'application/javascript'
    elif ext == 'css':
        mimetype = 'text/css'
    else:
        mimetype = 'text/plain'
    
    return send_from_directory('static', path, mimetype=mimetype)


@socketio.on('connect')
def handle_connect():
    print('Client connected')

@socketio.on('disconnect')
def handle_disconnect():
    print('Client disconnected')

@socketio.on('message')
def handle_message(message):
    print('Received message: ' + message)
    # 可以在这里处理从前端发送的消息

# 清空历史消息
@socketio.on('clear_history')
def handle_clear_history():
    print('Clear history')
    ernie_api.clear_history()

@socketio.on('user_input')
def handle_message(message):
    print(f"用户提交信息: {message}")
    def on_func_call(func_name, func_args, bot_thoughts):
        print(f"[!] 调用了函数{func_name}，参数为{func_args}")
        notification = {
            "title": f"调用了函数{func_name}",
            "content": f"参数为{func_args}",
            "thoughts": f"模型思考过程：{bot_thoughts}"
        }
        socketio.emit("notification", notification)
    def on_func_complete(func_name, func_args, result):
        print(f"[!] 函数{func_name}调用完成，参数为{func_args}，结果为{result}")
        # notification = f"函数{func_name}调用完成，参数为{func_args}，结果为{result}"
        notification = {
            "title": f"函数{func_name}调用完成",
            "content": f"参数为{func_args}，结果为{result}"
        }
        socketio.emit("notification", notification)
    
    def on_bot_reply(reply):
        print(f"[!] 机器人回复: {reply}")
        try:
            emotion, reply = reply.split("|", 1)
            assert emotion.lower() in ["happy", "angry", "calm"]
        except:
            print("Error: ", reply)
            emotion = "CALM"
        socketio.emit("bot_reply", {"emotion": emotion, "content": reply})
        # minimax.text2audio(reply)

    ernie_api.chat(message, on_func_call=on_func_call, on_func_complete=on_func_complete, on_bot_reply=on_bot_reply)
    




        
# # 启动发送事件的线程
# socketio.start_background_task(send_event)

if __name__ == '__main__':
    app.logger.setLevel(logging.DEBUG)
    socketio.run(app, allow_unsafe_werkzeug=True, port=8080, host="0.0.0.0")
